package cn.bocweb.spinning.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.CompanyList2Bean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.activity.CompanyInfoActivity;
import cn.bocweb.spinning.view.adapter.SearchCompanyResultAdapter;
import de.greenrobot.event.EventBus;

/**
 * Created by chenchangxing on 16/3/10.
 */
public class CompanySearchResultFragment extends Fragment {

    SearchCompanyResultAdapter searchCompanyResultAdapter;
    List<CompanyList2Bean.DataBean> list;
    int page = 0;
    UserPresenter presenter;
    String city = "", cate = "", keyword, userid;
    boolean isLastPage, isSlidingToLast;


    @Bind(R.id.company_search_result_list)
    RecyclerView companySearchResultList;
    @Bind(R.id.refresh)
    SwipeRefreshLayout refresh;

    public CompanySearchResultFragment() {
        list = new ArrayList<>();
        presenter = new UserPresenterImp();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_company_search_result, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        searchCompanyResultAdapter = new SearchCompanyResultAdapter(list);
        initList();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initList() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);

        companySearchResultList.setLayoutManager(manager);
        companySearchResultList.setAdapter(searchCompanyResultAdapter);

        searchCompanyResultAdapter.setOnItemClickListener(new SearchCompanyResultAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String id, String collect) {
                Intent intent = new Intent(getActivity(), CompanyInfoActivity.class);
                intent.putExtra(Constant.TO_COMPANY, id);
                intent.putExtra(Constant.TO_COMPANY_COLLECT, collect);
                startActivity(intent);
            }
        });

        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                list.clear();
                presenter.getCompanyList2(city, cate, keyword, userid, page);
            }
        });

        refresh.setColorSchemeColors(new int[] {R.color.colorPrimary});

        companySearchResultList.addOnScrollListener(new RecyclerView.OnScrollListener(){
            //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                LinearLayoutManager manager = (LinearLayoutManager)recyclerView.getLayoutManager();
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();

                    // 判断是否滚动到底部，并且是向右滚动
                    if (lastVisibleItem == (totalItemCount -1) && isSlidingToLast) {
                        //加载更多功能的代码
                        if (!isLastPage) {
                            page++;
                            presenter.getCompanyList2(city, cate, keyword, userid, page);
                        } else {
                            DeviceUtil.MyToast(getActivity(), "已经是最后一页");
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if(dy > 0){
                    //大于0表示，正在向右滚动
                    isSlidingToLast = true;
                }else{
                    //小于等于0 表示停止或向左滚动
                    isSlidingToLast = false;
                }

            }
        });
    }

    public void requestCompanySearch(String city, String cate, String keyword, String userid) {
        this.city = city;
        this.cate = cate;
        this.keyword = keyword;
        this.userid = userid;

        presenter.getCompanyList2(city, cate, keyword, userid, page);
    }

    public void onEventMainThread(CompanyList2Bean bean) {
        if (refresh.isRefreshing()) {
            refresh.setRefreshing(false);
        }
        if (bean.getReturn_code() == 0) {
            list.clear();
            list.addAll(bean.getData());
            searchCompanyResultAdapter.notifyDataSetChanged();
        } else if (bean.getReturn_code() == -202) {
            isLastPage = true;
            DeviceUtil.MyToast(getActivity(), "已经是最后一页");
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
